#ifndef NVSMANAGER_H
#define NVSMANAGER_H

#include <stdint.h>
#include <stddef.h>
  
#include "nvs_flash.h"
#include "nvs.h"

#define NVS_NAMESPACE "wifi_config"
// ---------------- NVS ----------------
static void save_wifi_config(const char *ssid, const char *password)
{
    nvs_handle_t handle;
    if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &handle) == ESP_OK)
    {
        nvs_set_str(handle, "ssid", ssid);
        nvs_set_str(handle, "password", password);
        nvs_commit(handle);
        nvs_close(handle);
    }
}

static bool load_wifi_config(char *ssid, size_t ssid_size, char *password, size_t pass_size)
{
    nvs_handle_t handle;
    bool success = false;
    if (nvs_open(NVS_NAMESPACE, NVS_READONLY, &handle) == ESP_OK)
    {
        size_t ssid_len = ssid_size;
        size_t pass_len = pass_size;
        if (nvs_get_str(handle, "ssid", ssid, &ssid_len) == ESP_OK &&
            nvs_get_str(handle, "password", password, &pass_len) == ESP_OK)
        {
            success = true;
        }
        nvs_close(handle);
    }
    return success;
}

// 清除wifi的账号和密码
static void erase_wifi_config()
{
    nvs_handle_t handle;
    if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &handle) == ESP_OK)
    {
        nvs_erase_key(handle, "ssid");
        nvs_erase_key(handle, "password");
        nvs_commit(handle);
        nvs_close(handle);
    }
}

#endif // NVSMANAGER_H
